package top.xiaoazi.futureletterserver.utils;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


@Component
public class CryptoAESUtils {

    private static final String SECRET_KEY = "your-secret-key-12311111"; // 请确保这与前端使用的密钥相同

    /**
     * 解密
     * @param encryptedData
     * @return
     * @throws Exception
     */
    public String decrypt(String encryptedData) throws Exception {
        String[] arr = encryptedData.split("&");
        String ciphertextBase64 = arr[0]; // 加密数据
        String ivBase64 = arr[1]; // iv

        byte[] keyBytes = SECRET_KEY.getBytes("UTF-8");
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

        byte[] iv = Base64.getDecoder().decode(ivBase64);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        byte[] ciphertext = Base64.getDecoder().decode(ciphertextBase64);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

        byte[] decryptedBytes = cipher.doFinal(ciphertext);

        return new String(decryptedBytes, "UTF-8");
    }
}
